import globalvar
import threading
from threading import Thread

import importlib
def dynamic_import(module):
    return importlib.import_module(module)


import globalvar

globalvar._init()

global dict_strategy, dict_strategyrun
# 策略文件名称
dict_strategy = ['MA策略', 'EMA策略', '3tick多空策略', '2根M1多空策略']
# 保存策略开启状态
dict_strategyrun = [1, 1, 1, 1]

readstrategyinstrumentIDstaste = 1


def readstrategyinstrumentID(strategyname):
    # 每次TICK都读取，可改为只读取一次
    global dict_strategyinstrument
    global readstrategyinstrumentIDstaste
    if readstrategyinstrumentIDstaste == 1:
        readstrategyinstrumentIDstaste = 0
        dict_tick = {}
        globalvar.dict_strategyinstrument[strategyname] = dict_tick
        with open('strategyfile\\' + strategyname + '.csv', 'r') as f:
            for line in f:
                print(strategyname + ' 策略对以下合约生效： ' + line)
                linelist = line.strip('\n').split(',')
                for k in iter(linelist):
                    globalvar.dict_strategyinstrument[strategyname][k] = k
                    # print('读取策略'+strategyname+' 交易合约：'+globalvar.dict_strategyinstrument[strategyname][line])


def strategymanager(marketdata):
    if globalvar.tradestate:
        # 定义跨模块全局变量
        globalvar.set_value('key1', 'Value1')
        globalvar.set_value('key2', 'Value2')
        '''
        module1 = dynamic_import('strategyfile.strategy1')
        module1.main(marketdata)
        module2 = dynamic_import('strategyfile.strategy2')
        module2.main(marketdata)
        return
        '''
        global dict_strategy, dict_strategyrun
        # 多个策略分别计算
        try:
            for k in dict_strategy:
                # print("strategyfile (%s) %s" % (ui.dict_strategy.index(k) + 1, k))
                print("(%s) %s" % (dict_strategy.index(k) + 1, k))
                if dict_strategyrun[int(dict_strategy.index(k))] == 1:
                    # print('允许运行该策略 %s' % k)
                    # 读取策略文件对应生效的合约文件，与策略文件同名，后缀名是.csv
                    readstrategyinstrumentID(k)
                    module = dynamic_import('strategyfile.' + k)
                    module.OnTick(marketdata, k)
        except Exception as e:
            print("strategymanager Error:" + repr(e))
    else:
        print("”启动策略自动交易按钮“未开启")



class MyStrategyMangement(object):
    # 多进程策略管理
    list_hwnd = []

    def StartStrategyProcess(self, msg):
        print("-->创建策略进程: ", msg[0], msg[1])
        sp = StrategyProcess(msg[0])
        thidprocesshwnd = sp.GetProcessHwnd()
        print('进程句柄返回值： ' + str(thidprocesshwnd))
        self.list_hwnd.append(thidprocesshwnd)
        return ("完成创建策略进程: " + msg[0])

    def CreatStrategyProcess(self):
        # 进程池，用于策略计算，将回调函数注册给C++ DLL，形成多个进程实例，在多进程下运行策略计算
        pool = multiprocessing.Pool(processes=4)
        result = []
        for i in range(4):
            msg = ['MA策略.py', i]
            result.append(pool.apply_async(self.StartStrategyProcess, (msg,)))

        # pool.close()
        # pool.join()
        for res in result:
            print("-->进程返回值：", res.get())

    def GetStrategyMode(self):
        try:
            # 实例化configParser对象
            config = configparser.ConfigParser()
            # read读取ini文件
            config.read('VNStrategyProcess.ini', encoding='utf-8')
            if config.getint('setting', 'mode') == 1:
                print("当前策略模式：单线程模式执行策略运算，仅支持.py策略文件")
            elif config.getint('setting', 'mode') == 2:
                print("当前策略模式：C++策略管理器，C++多进程模式执行策略运算，支持.py策略文件和.dll策略文件")
                self.CreatStrategyProcess()
        except Exception as e:
            print("GetStrangeMode Error:" + repr(e))

# 逻辑可能存在问题
class RegSpOnStrategyCalculate(Thread):
    def __init__(self, name, sp):
        super().__init__()
        self.name = name
        self.sp = sp

    def run(self):
        self.sp.VNRegOnStrategyCalculate()